<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="JUST DO IT.">
<meta property="og:type" content="website">
<meta property="og:title" content="Srtian&#39;Blog">
<meta property="og:url" content="http://srtian96.gitee.io/blog/page/4/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="JUST DO IT.">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Srtian&#39;Blog">
<meta name="twitter:description" content="JUST DO IT.">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/page/4/"/>





  <title>Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left 
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/06/07/初探 async await/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/06/07/初探 async await/" itemprop="url">初探 async await</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-07T22:24:13+08:00">
                2018-06-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,379
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>最近准备学习Koa，因此将JavaScript的异步操作又理了一遍，发现还是async await写起来比较直白，不愧是现在JavaScript异步操作的终极解决方案。</p>
<h3 id="一、Async-Await的初识"><a href="#一、Async-Await的初识" class="headerlink" title="一、Async/Await的初识"></a>一、Async/Await的初识</h3><h4 id="Async-Await的含义"><a href="#Async-Await的含义" class="headerlink" title="Async/Await的含义"></a>Async/Await的含义</h4><p><strong>Async</strong> - 定义异步函数(<em>async function someName(){…}</em>)</p>
<ul>
<li>自动把函数转换为 Promise</li>
<li>当调用异步函数时，函数返回值会被 resolve 处理</li>
<li>异步函数内部可以使用 await</li>
</ul>
<p><strong>Await</strong> - 暂停异步函数的执行 (<em>var result = await someAsyncCall()</em>)</p>
<ul>
<li>当使用在 Promise 前面时，await 等待 Promise 完成，并返回 Promise 的结果</li>
<li>await 只能和 Promise 一起使用，不能和 callback 一起使用</li>
<li>await 只能用在 async 函数中</li>
</ul>
<h4 id="Async-Await-和-Generator"><a href="#Async-Await-和-Generator" class="headerlink" title="Async/Await 和 Generator"></a>Async/Await 和 Generator</h4><p>async 函数是ES6所提出的，本质上是Generator函数的语法糖，但它在以下四点做了长足的改进：</p>
<ul>
<li>内置执行器：Generator 函数的执行必须依靠执行器，而 async 函数则自带执行器，调用的方式和普通函数调用一样。</li>
<li>语义化：较之于Generator 函数的 * 和 yield，async/await无疑是更为语义化。</li>
<li>返回的值是Promise: async 函数返回值是Promise对象，及哦啊哈子与Generator 函数所返回的Lterator对象更加方便，可以直接使用 then() 方法进行链式调用。</li>
<li>适用范围更广： co 模块约定，yield 命令后面只能是 Thunk 函数或 Promise对象。而 async 函数的 await 命令后面则可以是 Promise 或者 原始类型的值。</li>
</ul>
<h3 id="二、async-语法"><a href="#二、async-语法" class="headerlink" title="二、async 语法"></a>二、async 语法</h3><p>首先 async 函数返回一个 Promise 对象，也就是说 async 函数内部 return 返回的值，会成为 then 方法回调函数的参数，等同于 return Promise.resolve(value)。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span>  <span class="title">f</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'hello async'</span></span><br><span class="line">&#125;;</span><br><span class="line">f().then( <span class="function">(<span class="params">v</span>) =&gt;</span> <span class="built_in">console</span>.log(v)) </span><br><span class="line"></span><br><span class="line"><span class="comment">// hello async</span></span><br></pre></td></tr></table></figure>
<p>其次 async 函数所返回的 Promise 对象，必须等到内部所有的 await 命令的 Promise 对象执行完成后，才会发生状态改变。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> delay = <span class="function"><span class="params">timeout</span> =&gt;</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span>=&gt;</span> setTimeout(resolve, <span class="built_in">console</span>.log(timeout) timeout))</span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">await</span> delay(<span class="number">1000</span>)</span><br><span class="line">    <span class="keyword">await</span> delay(<span class="number">2000</span>)</span><br><span class="line">    <span class="keyword">await</span> delay(<span class="number">3000</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'end'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">f().then(<span class="function"><span class="params">v</span> =&gt;</span> <span class="built_in">console</span>.log(v)) <span class="comment">// 需要等待6秒后才会输出"end"</span></span><br></pre></td></tr></table></figure></p>
<p>正常情况下，await 命令后面跟着的是 Promise ，如果不是的话，也会被转换成一个立即 resolve 的 Promise。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span>  <span class="title">f</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">await</span> <span class="number">1</span></span><br><span class="line">&#125;;</span><br><span class="line">f().then( <span class="function">(<span class="params">v</span>) =&gt;</span> <span class="built_in">console</span>.log(v))  <span class="comment">// 1</span></span><br></pre></td></tr></table></figure>
<p>最后如果 async 函数内部抛出异常，则会导致返回的 Promise 对象状态变为 reject 状态。抛出的错误而会被 catch 方法回调函数接收到。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">e</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'error'</span>);</span><br><span class="line">&#125;</span><br><span class="line">e().then(<span class="function"><span class="params">v</span> =&gt;</span> <span class="built_in">console</span>.log(v))</span><br><span class="line">.catch( <span class="function"><span class="params">e</span> =&gt;</span> <span class="built_in">console</span>.log(e));</span><br></pre></td></tr></table></figure>
<h3 id="三、async和其他异步操作的比较"><a href="#三、async和其他异步操作的比较" class="headerlink" title="三、async和其他异步操作的比较"></a>三、async和其他异步操作的比较</h3><p>直接上代码：<br>首先定义一个可以获取 github user 的 fetch 方法：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fetchUser</span>(<span class="params"></span>) </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        fetch(<span class="string">'https://api.github.com/users/srtian'</span>)</span><br><span class="line">        .then(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">            resolve(data.json())</span><br><span class="line">        &#125;, (error) =&gt; &#123;</span><br><span class="line">            reject(error)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="Promise"><a href="#Promise" class="headerlink" title="Promise"></a>Promise</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getUserByPromise</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    fetchUser()</span><br><span class="line">        .then(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(data)</span><br><span class="line">        &#125;, (error) =&gt; &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(error)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line">getUserByPromise();</span><br></pre></td></tr></table></figure>
<p>这样看起来使用 Promise 来进行异步操作好像非常不错，但有个问题是，一旦then变多了，代码将会变得非常冗长和复杂，且语义化不明显，代码流程不能很好的表示执行的流程。</p>
<h4 id="Generator"><a href="#Generator" class="headerlink" title="Generator"></a>Generator</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> *<span class="title">fetchUserByGenerator</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> user = <span class="keyword">yield</span> fetchUser()</span><br><span class="line">    <span class="keyword">return</span> user</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> g = fetchUserByGenerator()</span><br><span class="line"><span class="keyword">const</span> result = g.next().value</span><br><span class="line">result.then(<span class="function">(<span class="params">v</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(v)</span><br><span class="line">&#125;, (error) =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(error)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>Generator 的方式解决了 Promise 的一些问题，流程更加直观、语义化。但是 Generator 的问题在于，函数的执行需要依靠执行器，每次都需要通过 g.next() 的方式去执行。而且虽然语义上有所进步，但 * 和 yield 明显还是不能满足我们对语义化直观观察的需要。</p>
<h4 id="async"><a href="#async" class="headerlink" title="async"></a>async</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">getUserByAsync</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">     <span class="keyword">let</span> user = <span class="keyword">await</span> fetchUser()</span><br><span class="line">     <span class="keyword">return</span> user</span><br><span class="line"> &#125;</span><br><span class="line">getUserByAsync()</span><br><span class="line">.then(<span class="function"><span class="params">v</span> =&gt;</span> <span class="built_in">console</span>.log(v))</span><br></pre></td></tr></table></figure>
<p>而 async/await 则很好的解决了上面两种异步操作的一些问题。首先使用同步的方法来写异步，代码非常清晰直观；其次使用async和await，在语义上非常好，一眼就能看出代码执行的顺序；最后 async 函数自带执行器，执行的时候无需手动加载。</p>
<h3 id="四、其他"><a href="#四、其他" class="headerlink" title="四、其他"></a>四、其他</h3><h4 id="错误处理"><a href="#错误处理" class="headerlink" title="错误处理"></a>错误处理</h4><p>除了上面的那些东西，Async 函数的错误处理也需要额外注意：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a</span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">await</span> <span class="built_in">Promise</span>.reject(<span class="string">'error'</span>)</span><br><span class="line">    a = <span class="keyword">await</span> <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">f().then(<span class="function"><span class="params">v</span> =&gt;</span> <span class="built_in">console</span>.log(a))</span><br></pre></td></tr></table></figure>
<p>上面的 a = await 1 没有执行，这是由于在 async 函数中，只要有一个 await 出现 reject 状态，那么后面的 await 都不会被执行。所以我们就需要使用 try/catch 来解决这个问题：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a</span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">correct</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">await</span> <span class="built_in">Promise</span>.reject(<span class="string">'error'</span>)</span><br><span class="line">    &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(error)</span><br><span class="line">    &#125;</span><br><span class="line">    a = <span class="keyword">await</span> <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> a</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">correct().then(<span class="function"><span class="params">v</span> =&gt;</span> <span class="built_in">console</span>.log(a)) <span class="comment">// 1</span></span><br></pre></td></tr></table></figure>
<h4 id="并行"><a href="#并行" class="headerlink" title="并行"></a>并行</h4><p>当我们需要使用并行进行加载时，使用async可能可以实现，但这是很低效的比如这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">await a()</span><br><span class="line">await b()</span><br><span class="line">await c()</span><br><span class="line">await d()</span><br></pre></td></tr></table></figure>
<p>换成回调就是这样的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a(() =&gt; &#123;</span><br><span class="line">  b(() =&gt; &#123;</span><br><span class="line">    c(() =&gt; &#123;</span><br><span class="line">      d()</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>然而我们发现，原始代码中，函数 c 可以与 a 同时执行，但 async/await 语法会让我们倾向于在 b 执行完后，再执行 c。</p>
<p>所以我们其实可以这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">async function ab() &#123;</span><br><span class="line">  await a()</span><br><span class="line">  b()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">async function cd() &#123;</span><br><span class="line">  await c()</span><br><span class="line">  d()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Promise.all([ab(), cd()])</span><br></pre></td></tr></table></figure>
<p>参考资料：</p>
<p><a href="https://segmentfault.com/a/1190000014753495" target="_blank" rel="noopener">https://segmentfault.com/a/1190000014753495</a></p>
<p><a href="https://juejin.im/post/596e142d5188254b532ce2da" target="_blank" rel="noopener">https://juejin.im/post/596e142d5188254b532ce2da</a></p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/06/02/解读Redux源码/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/06/02/解读Redux源码/" itemprop="url">Redux源码解读</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-02T19:30:17+08:00">
                2018-06-02
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/React/" itemprop="url" rel="index">
                    <span itemprop="name">React</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,026
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>作为React全家桶的一份子，MVVM中的VM，Redux为react提供了严谨周密的状态管理。但Redux本身是有点难度的，虽然学习了React也有一段时间了，自我感觉算是入了门，也知道redux的大概流程。但其背后诸如createstore,applymiddleware等API背后到底发生了什么事情，我其实还是不怎么了解的，因此最近花了几天时间阅读了Redux的源码，写下文章纪录一下自己看源码的一些理解。(此文章会随着自己对redux的理解的加深持续更新改进)</p>
<h3 id="一、源码结构（redux4-0版本）"><a href="#一、源码结构（redux4-0版本）" class="headerlink" title="一、源码结构（redux4.0版本）"></a>一、源码结构（redux4.0版本）</h3><p>Redux是出了名的短小精悍（恩，这个形容很贴切），只有2kb大小，且没有任何依赖。它将所有的脏活累活都交给了中间件去处理，自己保持着很好的纯洁性。再加上redux作者在redux的源码上，也附加了大量的注释，因此redux的源码读起来还是不算难的。</p>
<p>先来看看redux的源码结构，也就是src目录下的代码：</p>
<p><img src="https://gitee.com/uploads/images/2018/0602/103801_e16b3fc7_1575229.png" alt="源码结构" title="Redux源码结构图.PNG"></p>
<p>其中utils是工具函数，主要是作为辅助几个核心API，因此不作讨论。<br>（注：由于篇幅的问题，下面代码很多都删除了官方注释，和较长的warn）</p>
<h3 id="二、具体组成"><a href="#二、具体组成" class="headerlink" title="二、具体组成"></a>二、具体组成</h3><p>index.js是redux的入口函数具体代码如下：</p>
<h4 id="2-1-index-js"><a href="#2-1-index-js" class="headerlink" title="2.1 index.js"></a>2.1 index.js</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> createStore <span class="keyword">from</span> <span class="string">'./createStore'</span></span><br><span class="line"><span class="keyword">import</span> combineReducers <span class="keyword">from</span> <span class="string">'./combineReducers'</span></span><br><span class="line"><span class="keyword">import</span> bindActionCreators <span class="keyword">from</span> <span class="string">'./bindActionCreators'</span></span><br><span class="line"><span class="keyword">import</span> applyMiddleware <span class="keyword">from</span> <span class="string">'./applyMiddleware'</span></span><br><span class="line"><span class="keyword">import</span> compose <span class="keyword">from</span> <span class="string">'./compose'</span></span><br><span class="line"><span class="keyword">import</span> warning <span class="keyword">from</span> <span class="string">'./utils/warning'</span></span><br><span class="line"><span class="keyword">import</span> __DO_NOT_USE__ActionTypes <span class="keyword">from</span> <span class="string">'./utils/actionTypes'</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isCrushed</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"><span class="keyword">if</span> (</span><br><span class="line">  process.env.NODE_ENV !== <span class="string">'production'</span> &amp;&amp;</span><br><span class="line">  <span class="keyword">typeof</span> isCrushed.name === <span class="string">'string'</span> &amp;&amp;</span><br><span class="line">  isCrushed.name !== <span class="string">'isCrushed'</span></span><br><span class="line">) &#123;</span><br><span class="line">  warning(</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> &#123;</span><br><span class="line">  createStore,</span><br><span class="line">  combineReducers,</span><br><span class="line">  bindActionCreators,</span><br><span class="line">  applyMiddleware,</span><br><span class="line">  compose,</span><br><span class="line">  __DO_NOT_USE__ActionTypes</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中isCrushed函数是用于验证在非生产环境下 Redux 是否被压缩，如果被压缩就会给开发者一个 warn 的提示。</p>
<p>在最后index.js 会暴露 createStore, combineReducers, bindActionCreators, applyMiddleware, compose 这几个redux最主要的API以供大家使用。</p>
<h4 id="2-2-creatStore"><a href="#2-2-creatStore" class="headerlink" title="2.2 creatStore"></a>2.2 creatStore</h4><p>createStore函数接受三个参数：</p>
<ul>
<li>reducer：是一个函数，返回下一个状态，接受两个参数：当前状态 和 触发的 action；</li>
<li>preloadedState：初始状态对象，可以很随意指定，比如服务端渲染的初始状态，但是如果使用 combineReducers 来生成 reducer，那必须保持状态对象的 key 和 combineReducers 中的 key 相对应；</li>
<li>enhancer：是store 的增强器函数，可以指定为中间件，持久化 等，但是这个函数只能用 Redux 提供的 applyMiddleware 函数来进行生成</li>
</ul>
<p>下面就是creactStore的源码，由于整体源码过长，且 subscribe 和 dispatch 函数也挺长的，所以就将 subscribe 和 dispatch 单独提出来细讲。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> $$observable <span class="keyword">from</span> <span class="string">'symbol-observable'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> ActionTypes <span class="keyword">from</span> <span class="string">'./utils/actionTypes'</span></span><br><span class="line"><span class="keyword">import</span> isPlainObject <span class="keyword">from</span> <span class="string">'./utils/isPlainObject'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">createStore</span>(<span class="params">reducer, preloadedState, enhancer</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> preloadedState === <span class="string">'function'</span> &amp;&amp; <span class="keyword">typeof</span> enhancer === <span class="string">'undefined'</span>) &#123;</span><br><span class="line">    enhancer = preloadedState</span><br><span class="line">    preloadedState = <span class="literal">undefined</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// enhancer应该为一个函数</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> enhancer !== <span class="string">'undefined'</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> enhancer !== <span class="string">'function'</span>) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Expected the enhancer to be a function.'</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//enhancer 接受 createStore 作为参数，对  createStore 的能力进行增强，并返回增强后的  createStore 。</span></span><br><span class="line">    <span class="comment">//  然后再将  reducer 和  preloadedState 作为参数传给增强后的  createStore ，最终得到生成的 store</span></span><br><span class="line">    <span class="keyword">return</span> enhancer(createStore)(reducer, preloadedState)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// reducer必须是函数</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> reducer !== <span class="string">'function'</span>) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Expected the reducer to be a function.'</span>)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 初始化参数</span></span><br><span class="line">  <span class="keyword">let</span> currentReducer = reducer   <span class="comment">// 当前整个reducer</span></span><br><span class="line">  <span class="keyword">let</span> currentState = preloadedState   <span class="comment">// 当前的state,也就是getState返回的值</span></span><br><span class="line">  <span class="keyword">let</span> currentListeners = []  <span class="comment">// 当前的订阅store的监听器</span></span><br><span class="line">  <span class="keyword">let</span> nextListeners = currentListeners <span class="comment">// 下一次的订阅</span></span><br><span class="line">  <span class="keyword">let</span> isDispatching = <span class="literal">false</span> <span class="comment">// 是否处于 dispatch action 状态中, 默认为false</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 这个函数用于确保currentListeners 和 nextListeners 是不同的引用</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">ensureCanMutateNextListeners</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (nextListeners === currentListeners) &#123;</span><br><span class="line">      nextListeners = currentListeners.slice()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 返回state</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">getState</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (isDispatching) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">        ......</span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> currentState</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 添加订阅</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">subscribe</span>(<span class="params">listener</span>) </span>&#123;</span><br><span class="line">  ......</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="comment">// 分发action</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">action</span>) </span>&#123;</span><br><span class="line">    ......</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//这个函数主要用于 reducer 的热替换，用的少</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">replaceReducer</span>(<span class="params">nextReducer</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> nextReducer !== <span class="string">'function'</span>) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Expected the nextReducer to be a function.'</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 替换reducer</span></span><br><span class="line">    currentReducer = nextReducer</span><br><span class="line">    <span class="comment">// 重新进行初始化</span></span><br><span class="line">    dispatch(&#123; <span class="attr">type</span>: ActionTypes.REPLACE &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 没有研究，暂且放着，它是不直接暴露给开发者的，提供了给其他一些像观察者模式库的交互操作。</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">observable</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    ......</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 创建一个store时的默认state</span></span><br><span class="line">  <span class="comment">// 用于填充初始的状态树</span></span><br><span class="line">  dispatch(&#123; <span class="attr">type</span>: ActionTypes.INIT &#125;)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    dispatch,</span><br><span class="line">    subscribe,</span><br><span class="line">    getState,</span><br><span class="line">    replaceReducer,</span><br><span class="line">    [$$observable]: observable</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="subscribe"><a href="#subscribe" class="headerlink" title="subscribe"></a>subscribe</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">subscribe</span>(<span class="params">listener</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> listener !== <span class="string">'function'</span>) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Expected the listener to be a function.'</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (isDispatching) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">        ......</span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> isSubscribed = <span class="literal">true</span></span><br><span class="line">    <span class="comment">// 如果 nextListeners 和 currentListeners 是一个引用，重新复制一个新的</span></span><br><span class="line">    ensureCanMutateNextListeners()</span><br><span class="line">    nextListeners.push(listener)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">unsubscribe</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (!isSubscribed) &#123;</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (isDispatching) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">          .......</span><br><span class="line">        )</span><br><span class="line">      &#125;</span><br><span class="line">      </span><br><span class="line">      isSubscribed = <span class="literal">false</span></span><br><span class="line">      ensureCanMutateNextListeners()</span><br><span class="line">      <span class="keyword">const</span> index = nextListeners.indexOf(listener)</span><br><span class="line">      <span class="comment">// 从nextListeners里面删除，会在下次dispatch生效</span></span><br><span class="line">      nextListeners.splice(index, <span class="number">1</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p> 有时候有些人会觉得 store.subscribe 用的很少,其实不然，是 react-redux 隐式的为我们帮我们完成了这方面的工作。subscribe 函数可以给 store 的状态添加订阅监听，一旦我们调用了 dispatch 来分发 action ，所有的监听函数就会执行。而 nextListeners 就是储存当前监听函数的列表，当调用 subscribe，传入一个函数作为参数时，就会给 nextListeners 列表 push 这个函数。同时调用 subscribe 函数会返回一个 unsubscribe 函数，用来解绑当前传入的函数，同时在 subscribe 函数定义了一个 isSubscribed 标志变量来判断当前的订阅是否已经被解绑，解绑的操作就是从 nextListeners 列表中删除当前的监听函数。</p>
<h5 id="dispatch"><a href="#dispatch" class="headerlink" title="dispatch"></a>dispatch</h5><p>dispatch是redux中一个非常核心的方法，也是我们在日常开发中最常用的方法之一。dispatch函数是用来触发状态改变的，他接受一个 action 对象作为参数，然后 reducer 就可以根据 action 的属性以及当前 store 的状态，来生成一个新的状态，从而改变 store 的状态；<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">action</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// action 必须是一个对象</span></span><br><span class="line">    <span class="keyword">if</span> (!isPlainObject(action)) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">        ......</span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// type必须要有属性，不能是undefined</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> action.type === <span class="string">'undefined'</span>) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">        ......</span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 禁止在reducers中进行dispatch，因为这样做可能导致分发死循环，同时也增加了数据流动的复杂度</span></span><br><span class="line">    <span class="keyword">if</span> (isDispatching) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'Reducers may not dispatch actions.'</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      isDispatching = <span class="literal">true</span></span><br><span class="line">    <span class="comment">// 将当前的状态和 action 传给当前的reducer，用于生成最新的 state</span></span><br><span class="line">      currentState = currentReducer(currentState, action)</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;  </span><br><span class="line">      <span class="comment">// 派发完毕</span></span><br><span class="line">      isDispatching = <span class="literal">false</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 将nextListeners交给listeners</span></span><br><span class="line">    <span class="keyword">const</span> listeners = (currentListeners = nextListeners)</span><br><span class="line">    <span class="comment">// 在得到新的状态后，依次调用所有的监听器，通知状态的变更</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; listeners.length; i++) &#123;</span><br><span class="line">      <span class="keyword">const</span> listener = listeners[i]</span><br><span class="line">      listener()</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> action</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="2-3-compose-js"><a href="#2-3-compose-js" class="headerlink" title="2.3 compose.js"></a>2.3 compose.js</h4><p>compose 可以接受一组函数参数，从右到左来组合多个函数，然后返回一个组合函数。它的源码并不长，但设计的十分巧妙：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (funcs.length === <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="params">arg</span> =&gt;</span> arg</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (funcs.length === <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> funcs[<span class="number">0</span>]</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> funcs.reduce(<span class="function">(<span class="params">a, b</span>) =&gt;</span> (...args) =&gt; a(b(...args)))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>compose函数的作用其实其源码的注释里讲的很清楚了，比如下面这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">compose(funcA, funcB, funcC)</span><br></pre></td></tr></table></figure>
<p>其实它与这样是等价的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">compose(funcA(funcB(funcC())))</span><br></pre></td></tr></table></figure>
<p>ompose 做的只是让我们在写深度嵌套的函数时，避免了代码的向右偏移。</p>
<h4 id="2-4-applyMiddleware"><a href="#2-4-applyMiddleware" class="headerlink" title="2.4 applyMiddleware"></a>2.4 applyMiddleware</h4><p>applyMiddleware也是redux中非常重要的一个函数，设计的也非常巧妙，让人叹为观止。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">applyMiddleware</span>(<span class="params">...middlewares</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="params">createStore</span> =&gt;</span> (...args) =&gt; &#123;</span><br><span class="line">    <span class="comment">// 利用传入的createStore和reducer和创建一个store</span></span><br><span class="line">    <span class="keyword">const</span> store = createStore(...args)</span><br><span class="line">    <span class="keyword">let</span> dispatch = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">        <span class="string">`Dispatching while constructing your middleware is not allowed. `</span> +</span><br><span class="line">          <span class="string">`Other middleware would not be applied to this dispatch.`</span></span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> middlewareAPI = &#123;</span><br><span class="line">      getState: store.getState,</span><br><span class="line">      dispatch: <span class="function">(<span class="params">...args</span>) =&gt;</span> dispatch(...args)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 让每个 middleware 带着 middlewareAPI 这个参数分别执行一遍</span></span><br><span class="line">    <span class="keyword">const</span> chain = middlewares.map(<span class="function"><span class="params">middleware</span> =&gt;</span> middleware(middlewareAPI))</span><br><span class="line">    dispatch = compose(...chain)(store.dispatch)</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      ...store,</span><br><span class="line">      dispatch</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过上面的代码，我们可以看出 applyMiddleware 是个三级<strong>柯里化</strong>的函数。它将陆续的获得三个参数：第一个是 middlewares 数组，第二个是 Redux 原生的 createStore，最后一个是 reducer，也就是上面的…args；</p>
<p>applyMiddleware 利用 createStore 和 reducer 创建了一个 store，然后 store 的 getState 方法和 dispatch 方法又分别被直接和间接地赋值给 middlewareAPI 变量。</p>
<p>其中这一句我感觉是最核心的：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dispatch = compose(...chain)(store.dispatch)</span><br></pre></td></tr></table></figure></p>
<p>我特意将compose与applyMiddleware放在一块，就是为了解释这段代码。因此上面那段核心代码中，本质上就是这样的(假设…chain有三个函数)：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dispatch = f1(f2(f3(store.dispatch))))</span><br></pre></td></tr></table></figure>
<h4 id="2-5-combineReducers"><a href="#2-5-combineReducers" class="headerlink" title="2.5 combineReducers"></a>2.5 combineReducers</h4><p>combineReducers 这个辅助函数的作用就是，将一个由多个不同 reducer 函数作为 value 的 object 合并成一个最终的 reducer 函数，然后我们就可以对这个 reducer 调用 createStore 方法了。这在createStore的源码的注释中也有提到过。</p>
<p>并且合并后的 reducer 可以调用各个子 reducer，并把它们返回的结果合并成一个 state 对象。 由 combineReducers() 返回的 state 对象，会将传入的每个 reducer 返回的 state 按其传递给 combineReducers() 时对应的 key 进行命名。</p>
<p>下面我们来看源码，下面的源码删除了一些的检查判断，只保留最主要的源码：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">combineReducers</span>(<span class="params">reducers</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> reducerKeys = <span class="built_in">Object</span>.keys(reducers)</span><br><span class="line">  <span class="comment">// 有效的 reducer 列表</span></span><br><span class="line">  <span class="keyword">const</span> finalReducers = &#123;&#125;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; reducerKeys.length; i++) &#123;</span><br><span class="line">    <span class="keyword">const</span> key = reducerKeys[i]</span><br><span class="line">  <span class="keyword">const</span> finalReducerKeys = <span class="built_in">Object</span>.keys(finalReducers)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 返回最终生成的 reducer</span></span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">combination</span>(<span class="params">state = &#123;&#125;, action</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> hasChanged = <span class="literal">false</span></span><br><span class="line">    <span class="comment">//定义新的nextState</span></span><br><span class="line">    <span class="keyword">const</span> nextState = &#123;&#125;</span><br><span class="line">    <span class="comment">// 1，遍历reducers对象中的有效key，</span></span><br><span class="line">    <span class="comment">// 2，执行该key对应的value函数，即子reducer函数，并得到对应的state对象</span></span><br><span class="line">    <span class="comment">// 3，将新的子state挂到新的nextState对象上，而key不变</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; finalReducerKeys.length; i++) &#123;</span><br><span class="line">      <span class="keyword">const</span> key = finalReducerKeys[i]</span><br><span class="line">      <span class="keyword">const</span> reducer = finalReducers[key]</span><br><span class="line">      <span class="keyword">const</span> previousStateForKey = state[key]</span><br><span class="line">      <span class="keyword">const</span> nextStateForKey = reducer(previousStateForKey, action)</span><br><span class="line">      nextState[key] = nextStateForKey</span><br><span class="line">      hasChanged = hasChanged || nextStateForKey !== previousStateForKey</span><br><span class="line">    &#125;</span><br><span class="line">     <span class="comment">// 遍历一遍看是否发生改变，发生改变了返回新的state，否则返回原先的state</span></span><br><span class="line">    <span class="keyword">return</span> hasChanged ? nextState : state</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="2-6-bindActionCreators"><a href="#2-6-bindActionCreators" class="headerlink" title="2.6 bindActionCreators"></a>2.6 bindActionCreators</h4><p>bindActionCreators可以把一个 value 为不同 action creator 的对象，转成拥有同名 key 的对象。同时使用 dispatch 对每个 action creator 进行包装，以便可以直接调用它们。<br>bindActionCreators函数并不常用（反正我还没有怎么用过），惟一会使用到 bindActionCreators 的场景就是我们需要把 action creator 往下传到一个组件上，却不想让这个组件觉察到 Redux 的存在，并且不希望把 dispatch 或 Redux store 传给它。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 核心代码，并通过apply将this绑定起来</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bindActionCreator</span>(<span class="params">actionCreator, dispatch</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> dispatch(actionCreator.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>))</span><br><span class="line">  &#125;</span><br><span class="line">&#125; </span><br><span class="line"><span class="comment">// 这个函数只是把actionCreators这个对象里面包含的每一个actionCreator按照原来的key的方式全部都封装了一遍，核心代码还是上面的</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">bindActionCreators</span>(<span class="params">actionCreators, dispatch</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 如果actionCreators是一个函数，则说明只有一个actionCreator，就直接调用bindActionCreator</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> actionCreators === <span class="string">'function'</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> bindActionCreator(actionCreators, dispatch)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 如果是actionCreator是对象或者null的话，就会报错</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> actionCreators !== <span class="string">'object'</span> || actionCreators === <span class="literal">null</span>) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(</span><br><span class="line">    ... ... </span><br><span class="line">  &#125;</span><br><span class="line"> <span class="comment">// 遍历对象，然后对每个遍历项的 actionCreator 生成函数，将函数按照原来的 key 值放到一个对象中，最后返回这个对象</span></span><br><span class="line">  <span class="keyword">const</span> keys = <span class="built_in">Object</span>.keys(actionCreators)</span><br><span class="line">  <span class="keyword">const</span> boundActionCreators = &#123;&#125;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; keys.length; i++) &#123;</span><br><span class="line">    <span class="keyword">const</span> key = keys[i]</span><br><span class="line">    <span class="keyword">const</span> actionCreator = actionCreators[key]</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> actionCreator === <span class="string">'function'</span>) &#123;</span><br><span class="line">      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> boundActionCreators</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="小节"><a href="#小节" class="headerlink" title="小节"></a>小节</h3><p>看一遍redux，感觉设计十分巧秒，不愧是大佬的作品。这次看代码只是初看，往后随着自己学习的不断深入，还需多加研究，绝对还能得到更多的体会。</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/06/01/浏览器渲染原理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/06/01/浏览器渲染原理/" itemprop="url">浏览器渲染原理与过程</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-01T20:26:40+08:00">
                2018-06-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/浏览器/" itemprop="url" rel="index">
                    <span itemprop="name">浏览器</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,070
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="一、浏览器如何渲染网页"><a href="#一、浏览器如何渲染网页" class="headerlink" title="一、浏览器如何渲染网页"></a>一、浏览器如何渲染网页</h3><p>要了解浏览器渲染页面的过程，首先得知道一个名词——关键路径渲染。<strong>关键渲染路径</strong>（Critical Rendering Path）是指与当前用户操作有关的内容。例如用户在浏览器中打开一个页面，其中页面所显示的东西就是当前用户操作相关的内容，也就是浏览器从服务器那收到的HTML,CSS,JavaScript等相关资源，然后经过一系列处理后渲染出来的web页面。</p>
<p>而浏览器渲染的过程主要包括以下五步：</p>
<ul>
<li>浏览器将获取的HTML文档并解析成DOM树。</li>
<li>处理CSS标记，构成层叠样式表模型CSSOM(CSS Object Model)。</li>
<li>将DOM和CSSOM合并为渲染树(rendering tree)将会被创建，代表一系列将被渲染的对象。</li>
<li>渲染树的每个元素包含的内容都是计算过的，它被称之为布局layout。浏览器使用一种流式处理的方法，只需要一次pass绘制操作就可以布局所有的元素。</li>
<li>将渲染树的各个节点绘制到屏幕上，这一步被称为绘制painting.</li>
</ul>
<p>具体如下图过程如下图所示：</p>
<p><img src="https://user-gold-cdn.xitu.io/2018/2/22/161bb3c9b220f8cb?imageView2/0/w/1280/h/960/ignore-error/1" alt="Webkit"></p>
<p>需要注意的是，以上五个步骤并不一定一次性顺序完成，比如DOM或CSSOM被修改时，亦或是哪个过程会重复执行，这样才能计算出哪些像素需要在屏幕上进行重新渲染。而在实际情况中，JavaScript和CSS的某些操作往往会多次修改DOM或者CSSOM。</p>
<p>下面我们就来详细的了解一下这几个过程及需要注意的事项。</p>
<h3 id="二、浏览器渲染网页的具体流程"><a href="#二、浏览器渲染网页的具体流程" class="headerlink" title="二、浏览器渲染网页的具体流程"></a>二、浏览器渲染网页的具体流程</h3><h4 id="2-1-构建DOM树"><a href="#2-1-构建DOM树" class="headerlink" title="2.1 构建DOM树"></a>2.1 构建DOM树</h4><p>当浏览器客户端从服务器那接受到HTML文档后，就会遍历文档节点然后生成DOM树，DOM树结构和HTML标签一一对应。需要注意记下几点：</p>
<ol>
<li>DOM树在构建的过程中可能会被CSS和JS的加载而执行阻塞。（这在后面会详细介绍。）</li>
<li>display:none 的元素也会在DOM树中。</li>
<li>注释也会在DOM树中</li>
<li>script标签会在DOM树中</li>
</ol>
<h4 id="2-2-CSS解析"><a href="#2-2-CSS解析" class="headerlink" title="2.2 CSS解析"></a>2.2 CSS解析</h4><p>浏览器会解析CSS文件并生成CSS规则树，在过程中，每个CSS文件都会被分析成StyleSheet对象，每个对象都包括CSS规则，CSS规则对象包括对应的选择器和声明对象以及其他对象。<br>在这个过程需要注意的是：</p>
<ul>
<li>CSS解析可以与DOM解析同进行。</li>
<li>CSS解析与script的执行互斥 。</li>
<li>在Webkit内核中进行了script执行优化，只有在JS访问CSS时才会发生互斥。</li>
</ul>
<h4 id="2-3-构建渲染树（Rendr-tree-construction）"><a href="#2-3-构建渲染树（Rendr-tree-construction）" class="headerlink" title="2.3 构建渲染树（Rendr tree construction）"></a>2.3 构建渲染树（Rendr tree construction）</h4><p>通过DOM树和CSS规则树，浏览器就可以通过它两构建渲染树了。浏览器会先从DOM树的根节点开始遍历每个可见节点，让后对每个可见节点找到适配的CSS样式规则并应用。具体的规则有以下几点需要注意：</p>
<ul>
<li>Render Tree和DOM Tree不完全对应。</li>
<li>display: none的元素不在Render Tree中</li>
<li>visibility: hidden的元素在Render Tree中</li>
</ul>
<h4 id="2-4-渲染树布局-layout-of-the-render-tree"><a href="#2-4-渲染树布局-layout-of-the-render-tree" class="headerlink" title="2.4 渲染树布局(layout of the render tree)"></a>2.4 渲染树布局(layout of the render tree)</h4><p>布局阶段会从渲染树的更节点开始遍历，由于渲染树的每个节点都是一个Render Object对象，包含宽高，位置，背景色等样式信息。所以浏览器就可以通过这些样式信息来确定每个节点对象在页面上的确切大小和位置，布局阶段的输出就是我们常说的盒子模型，它会精确地捕获每个元素在屏幕内的确切位置与大小。需要注意的是：</p>
<ul>
<li>float元素，absoulte元素，fixed元素会发生位置偏移。</li>
<li>我们常说的脱离文档流，其实就是脱离Render Tree。</li>
</ul>
<h4 id="2-5-渲染树绘制（Painting-the-render-tree）"><a href="#2-5-渲染树绘制（Painting-the-render-tree）" class="headerlink" title="2.5 渲染树绘制（Painting the render tree）"></a>2.5 渲染树绘制（Painting the render tree）</h4><p>在绘制阶段，浏览器会遍历渲染树，调用渲染器的paint()方法在屏幕上显示其内容。渲染树的绘制工作是由浏览器的UI后端组件完成的。</p>
<h3 id="三、浏览器渲染网页的那些事儿"><a href="#三、浏览器渲染网页的那些事儿" class="headerlink" title="三、浏览器渲染网页的那些事儿"></a>三、浏览器渲染网页的那些事儿</h3><h4 id="3-1-阻塞渲染"><a href="#3-1-阻塞渲染" class="headerlink" title="3.1 阻塞渲染"></a>3.1 阻塞渲染</h4><p>前面我们有提到这方面的问题，说到资源的阻塞我们清楚的是，现代浏览器总是并行加载自语言。例如当HTML解析器被脚本阻塞时，解析器虽然会停止构建DOM，但仍然会辨识该脚本后面的资源，并进行预加载。且由于以下两点。浏览器会延迟 JavaScript 的执行和 DOM 构建：</p>
<ul>
<li>CSS 被默认被视为阻塞渲染的资源，因此浏览器将在 CSSOM 构建完毕前不会渲染任何已处理的内容。</li>
<li>JavaScript 不仅可以读取和修改 DOM 属性，还可以读取和修改 CSSOM 属性，因此CSS解析与script的执行互斥。</li>
</ul>
<p>正是由于以上这些原因，script标签的位置很重要我们在实际开发中应该尽量坚持以下两个原则：</p>
<ul>
<li>在引入顺序上，CSS 资源先于 JavaScript 资源。</li>
<li>JavaScript 应尽量少的去影响 DOM 的构建。</li>
</ul>
<h4 id="3-2-回流和重绘（reflow和repaint）"><a href="#3-2-回流和重绘（reflow和repaint）" class="headerlink" title="3.2 回流和重绘（reflow和repaint）"></a>3.2 回流和重绘（reflow和repaint）</h4><p>我们都知道HTML默认是流式布局的，但CSS和JS会打破这种布局，改变DOM的外观样式以及大小和位置。因此我们就需要知道两个概念:</p>
<ul>
<li>reflow（回流）：当浏览器发现某个部分发生了变化从而影响了布局，这个时候就需要倒回去重新渲染，大家称这个回退的过程叫 reflow。 常见的reflow是一些会影响页面布局的操作，诸如Tab，隐藏等。reflow 会从 html 这个 root frame 开始递归往下，依次计算所有的结点几何尺寸和位置，以确认是渲染树的一部分发生变化还是整个渲染树。reflow几乎是无法避免的，因为只要用户进行交互操作，就势必会发生页面的一部分的重新渲染，且通常我们也无法预估浏览器到底会reflow哪一部分的代码，因为他们会相互影响。</li>
<li>repaint（重绘）： repaint则是当我们改变某个元素的背景色、文字颜色、边框颜色等等不影响它周围或内部布局的属性时，屏幕的一部分要重画，但是元素的几何尺寸和位置没有发生改变。</li>
</ul>
<p>需要注意的是，display:none 会触发 reflow，而visibility: hidden属性则并不算是不可见属性，它的语义是隐藏元素，但元素仍然占据着布局空间，它会被渲染成一个空框，这在我们上面有提到过。所以 visibility:hidden 只会触发 repaint，因为没有发生位置变化。</p>
<p>我们不能避免reflow，但还是能通过一些操作来减少回流：</p>
<ol>
<li>用transform做形变和位移.</li>
<li>通过绝对位移来脱离当前层叠上下文，形成新的Render Layer。</li>
</ol>
<p>另外有些情况下，比如修改了元素的样式，浏览器并不会立刻reflow 或 repaint 一次，而是会把这样的操作积攒一批，然后做一次 reflow，这又叫异步 reflow 或增量异步 reflow。但是在有些情况下，比如 resize 窗口，改变了页面默认的字体等。对于这些操作，浏览器会马上进行 reflow。</p>
<h4 id="3-3-几条关于优化渲染效率的建议"><a href="#3-3-几条关于优化渲染效率的建议" class="headerlink" title="3.3 几条关于优化渲染效率的建议"></a>3.3 几条关于优化渲染效率的建议</h4><p>结合上文和我看到的一些文章，有以下几点可以优化渲染效率</p>
<ol>
<li>合法地去书写 HTML 和 CSS ，且不要忘了文档编码类型。</li>
<li>样式文件应当在 head 标签中，而脚本文件在 body 结束前，这样可以防止阻塞的方式。</li>
<li>简化并优化CSS选择器，尽量将嵌套层减少到最小。</li>
<li>尽量减少在 JavaScript 中进行DOM操作。</li>
<li>修改元素样式时，更改其class属性是性能最高的方法。</li>
<li>尽量用 transform 来做形变和位移</li>
</ol>
<p>参考文章：</p>
<p><a href="http://www.cnblogs.com/slly/p/6640761.html" target="_blank" rel="noopener">http://www.cnblogs.com/slly/p/6640761.html</a></p>
<p><a href="https://zhuanlan.zhihu.com/p/29418126" target="_blank" rel="noopener">https://zhuanlan.zhihu.com/p/29418126</a></p>
<p><a href="https://juejin.im/post/5a8e242c5188257a6b060000" target="_blank" rel="noopener">https://juejin.im/post/5a8e242c5188257a6b060000</a></p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/25/关于React setState的一些思考与心得/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/05/25/关于React setState的一些思考与心得/" itemprop="url">关于React setState的一些思考与心得</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-25T19:19:36+08:00">
                2018-05-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/React/" itemprop="url" rel="index">
                    <span itemprop="name">React</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,038
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>这篇文章主要是为了纪录一些自己对于setState的认识的不断深入的过程。我觉得这过程对我自己来说很有价值，不光是层层递进的了解一个API的执行机制，更对react总体的设计有了更为深入的认识。</p>
<h3 id="第一阶段-初识setState"><a href="#第一阶段-初识setState" class="headerlink" title="第一阶段 初识setState"></a>第一阶段 初识setState</h3><p>使用过React的应该都知道，在React中，一个组件中要读取当前状态需要访问this.state，但是更新状态却需要使用this.setState，不是直接在this.state上修改，就比如这样：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//读取状态</span></span><br><span class="line"><span class="keyword">const</span> count = <span class="keyword">this</span>.state.count；</span><br><span class="line"></span><br><span class="line"><span class="comment">//更新状态</span></span><br><span class="line"><span class="keyword">this</span>.setState(&#123;<span class="attr">count</span>: count + <span class="number">1</span>&#125;)；</span><br><span class="line"></span><br><span class="line"><span class="comment">//无意义的修改</span></span><br><span class="line"><span class="keyword">this</span>.state.count = count + <span class="number">1</span>;</span><br></pre></td></tr></table></figure></p>
<p>其实这主要有几点考虑，首先this.state说到底只是一个对象，单纯的去修改一个对象的值是毫无意义的，在React中只有去驱动UI的更新才有意义，因此虽然我们可以尝试直接改变this.state，但并没有驱动UI的重新渲染，因此这种操作也就毫无意义。也正是由于这个原因，我们就需要使用this.setState来驱动组件的更新过程。</p>
<p>然后在我刚学习React时，我就看见了这段很经典的代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">incrementMultiple</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123;<span class="attr">count</span>: <span class="keyword">this</span>.state.count + <span class="number">1</span>&#125;);</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123;<span class="attr">count</span>: <span class="keyword">this</span>.state.count + <span class="number">1</span>&#125;);</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123;<span class="attr">count</span>: <span class="keyword">this</span>.state.count + <span class="number">1</span>&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>作为一名JSer，我看完就毫不犹豫的想到，这不就是count的值加3么。但转眼看了下面的答案，光速打脸，实际的结果是state只增加了1。然后我就不由想到当时没怎么看懂的React文档中的一些话：状态更新可能是异步的，状态更新合并。恩，没毛病，因为异步且会合并，因此这三条语句合并为一条语句了，所以就只执行一次。然后就扭头溜了，并没有去思考一些深层次的问题。</p>
<h3 id="第二阶段-setState理解的进阶"><a href="#第二阶段-setState理解的进阶" class="headerlink" title="第二阶段 setState理解的进阶"></a>第二阶段 setState理解的进阶</h3><p>但是随着对React的理解的逐步加深，我开始对setState有了更加深的理解：</p>
<p>首先我意识到this.setState会通过引发一次组件的更新过程来引发重新绘制。也就是说setState的调用会引起React的更新生命周期的四个函数的依次调用：</p>
<ul>
<li>shouldComponentUpdate</li>
<li>componentWillUpdate</li>
<li>render</li>
<li>componentDidUpdate</li>
</ul>
<p>我们都知道，在React生命周期函数里，以render函数为界，无论是挂载过程和更新过程，在render之前的几个生命周期函数，this.state和Props都是不会发生更新的，直到render函数执行完毕后，this.state才会得到更新。（有一个例外：当shouldComponentUpdate函数返回false，这时候更新过程就被中断了，render函数也不会被调用了，这时候React不会放弃掉对this.state的更新的，所以虽然不调用render，依然会更新this.state。）</p>
<p>React的官方文档有提到过这么一句话：</p>
<blockquote>
<p>状态更新会合并（也就是说多次setstate函数调用产生的效果会合并）。</p>
</blockquote>
<p>起初我对这句话理解并不是很深刻,但按照官方文档的代码示例写了这么一段代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateName</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123;<span class="attr">Age</span>: <span class="string">'22'</span>&#125;)</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123;<span class="attr">Name</span>: <span class="string">'srtian'</span>&#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>果然执行结果与以下代码是等价的</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateName</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.setState(&#123;<span class="attr">Age</span>: <span class="string">'22'</span>, <span class="attr">Name</span>: <span class="string">'srtian&#125;)</span></span><br><span class="line"><span class="string">&#125;</span></span><br></pre></td></tr></table></figure>
<p>于是我将其理解为一个队列，每个this.setState()都会被合并起来，排成一排，到最后一次解决。但对其设计的原因并不理解，只知道这样有利于性能（也是在文档上看到的）。</p>
<p>直到理解上面React生命周期函数的原理后，我才理解了setState关于这个设计的意图。</p>
<p>前面我们提到过，每一次使用setState都会调用一次更新的生命周期，如果每一次this.setState()都调用一次上面那四个生命周期函数，虽然以上四个函数都是纯函数，性能浪费上还好说，但render函数会将结果拿去做Virtual DOM比较和更新DOM树，这个就比较费时间。因此，将多个this.setSate进行合并，render函数就能够将合并后的this.setState()的结果一次性的与Virtual DOM比较然后更新DOM树，这样就能够用有效的提升性能。</p>
<p>除此之外，我还认为setState的设计十分巧妙，一般来说只在render函数后才会进行更新this.state。这其实也避免了React16的Fiber可能会产生的一个问题：由于Fiber下的组件更新是可以中断，也就是说在一个组件的更新过程中，可能更新到一半的时候就由于其他原因而中断更新，回去做更重要的事情了，在做完更重要的事情后，再回来更新这个组件，这会导致前面的那些生命周期函数可能会执行多次。因此如果在render之前this.setState()就改变状态的话，很有可能就会导致组件状态的多次更新，从而导致组件状态的混乱。</p>
<h3 id="第三阶段-从源码理解setstate"><a href="#第三阶段-从源码理解setstate" class="headerlink" title="第三阶段 从源码理解setstate"></a>第三阶段 从源码理解setstate</h3><blockquote>
<p>这是React15.6版本，由于React16变动较大，setState的调用栈发生变动，因此仅供参考。</p>
</blockquote>
<p>经历了上面那个阶段，我算是对setState有那么一些理解了，但还是不能理解很多东西比如：this.setState()的是怎么合并的？setState()到底是怎样一种骚操作？…等等。然后我又看见了这段经典的代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Example</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="keyword">super</span>();</span><br><span class="line">    <span class="keyword">this</span>.state = &#123;</span><br><span class="line">      val: <span class="number">0</span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  componentDidMount() &#123;</span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;<span class="attr">val</span>: <span class="keyword">this</span>.state.val + <span class="number">1</span>&#125;);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.val);    <span class="comment">// 第 1 次 log</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;<span class="attr">val</span>: <span class="keyword">this</span>.state.val + <span class="number">1</span>&#125;);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.val);    <span class="comment">// 第 2 次 log</span></span><br><span class="line"></span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">this</span>.setState(&#123;<span class="attr">val</span>: <span class="keyword">this</span>.state.val + <span class="number">1</span>&#125;);</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.val);  <span class="comment">// 第 3 次 log</span></span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.setState(&#123;<span class="attr">val</span>: <span class="keyword">this</span>.state.val + <span class="number">1</span>&#125;);</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.val);  <span class="comment">// 第 4 次 log</span></span><br><span class="line">    &#125;, <span class="number">0</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>恩！按照我多年经验，这波操作我看不懂！</p>
<p><img src="https://tse1-mm.cn.bing.net/th?id=OIP.ZlvZC7ugr-G8oLHt_9NXTAHaDv&amp;w=200&amp;h=98&amp;c=8&amp;rs=1&amp;qlt=90&amp;dpr=1.25&amp;pid=3.1&amp;rm=2" alt="image"></p>
<p>于是硬着头皮打开了React源码，开始一波瞎分析：<br>首先就是setState了，可以看出它接受两个参数 partialState 和callback，其中 partialState 顾名思义就是部分 state，起这个名字也能就是想表达它的 state 没有改变（瞎猜的。。。）。以下是省略了一部分的代码，只看核心部分。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line">ReactComponent.prototype.setState = <span class="function"><span class="keyword">function</span>(<span class="params">partialState, callback</span>) </span>&#123;</span><br><span class="line">  invariant(</span><br><span class="line">    <span class="keyword">typeof</span> partialState === <span class="string">'object'</span> ||</span><br><span class="line">      <span class="keyword">typeof</span> partialState === <span class="string">'function'</span> ||</span><br><span class="line">      partialState == <span class="literal">null</span>,</span><br><span class="line">    <span class="string">'setState(...): takes an object of state variables to update or a '</span> +</span><br><span class="line">      <span class="string">'function which returns an object of state variables.'</span>,</span><br><span class="line">  );</span><br><span class="line">  <span class="keyword">this</span>.updater.enqueueSetState(<span class="keyword">this</span>, partialState);</span><br><span class="line">  <span class="keyword">if</span> (callback) &#123;</span><br><span class="line">    <span class="keyword">this</span>.updater.enqueueCallback(<span class="keyword">this</span>, callback, <span class="string">'setState'</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"> enqueueSetState: <span class="function"><span class="keyword">function</span>(<span class="params">publicInstance, partialState</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (__DEV__) &#123;</span><br><span class="line">      ReactInstrumentation.debugTool.onSetState();</span><br><span class="line">      warning(</span><br><span class="line">        partialState != <span class="literal">null</span>,</span><br><span class="line">        <span class="string">'setState(...): You passed an undefined or null state object; '</span> +</span><br><span class="line">          <span class="string">'instead, use forceUpdate().'</span>,</span><br><span class="line">      );</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> internalInstance = getInternalInstanceReadyForUpdate(</span><br><span class="line">      publicInstance,</span><br><span class="line">      <span class="string">'setState'</span>,</span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!internalInstance) &#123;</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> queue =</span><br><span class="line">      internalInstance._pendingStateQueue ||</span><br><span class="line">      (internalInstance._pendingStateQueue = []);</span><br><span class="line">    queue.push(partialState);</span><br><span class="line"></span><br><span class="line">    enqueueUpdate(internalInstance);</span><br><span class="line">  &#125;</span><br><span class="line"><span class="comment">// 通过enqueueUpdate执行state更新</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">enqueueUpdate</span>(<span class="params">component</span>) </span>&#123;</span><br><span class="line">  ensureInjected();</span><br><span class="line">  <span class="comment">// batchingStrategy是批量更新策略，isBatchingUpdates表示是否处于批量更新过程</span></span><br><span class="line">  <span class="comment">// 最开始默认值为false</span></span><br><span class="line">  <span class="keyword">if</span> (!batchingStrategy.isBatchingUpdates) &#123;</span><br><span class="line">    batchingStrategy.batchedUpdates(enqueueUpdate, component);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  dirtyComponents.push(component);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (component._updateBatchNumber == <span class="literal">null</span>) &#123;</span><br><span class="line">    component._updateBatchNumber = updateBatchNumber + <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 对_pendingElement, _pendingStateQueue, _pendingForceUpdate进行判断，</span></span><br><span class="line"><span class="comment">// _pendingStateQueue由于会对state进行修改，所以不为空，</span></span><br><span class="line"><span class="comment">// 然后会调用updateComponent方法</span></span><br><span class="line">performUpdateIfNecessary: <span class="function"><span class="keyword">function</span>(<span class="params">transaction</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>._pendingElement != <span class="literal">null</span>) &#123;</span><br><span class="line">      ReactReconciler.receiveComponent(</span><br><span class="line">        <span class="keyword">this</span>,</span><br><span class="line">        <span class="keyword">this</span>._pendingElement,</span><br><span class="line">        transaction,</span><br><span class="line">        <span class="keyword">this</span>._context,</span><br><span class="line">      );</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">this</span>._pendingStateQueue !== <span class="literal">null</span> || <span class="keyword">this</span>._pendingForceUpdate) &#123;</span><br><span class="line">      <span class="keyword">this</span>.updateComponent(</span><br><span class="line">        transaction,</span><br><span class="line">        <span class="keyword">this</span>._currentElement,</span><br><span class="line">        <span class="keyword">this</span>._currentElement,</span><br><span class="line">        <span class="keyword">this</span>._context,</span><br><span class="line">        <span class="keyword">this</span>._context,</span><br><span class="line">      );</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">this</span>._updateBatchNumber = <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br></pre></td></tr></table></figure></p>
<p>其中这段代码需要额外注意：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">  <span class="comment">// batchingStrategy是批量更新策略，isBatchingUpdates表示是否处于批量更新过程</span></span><br><span class="line">  <span class="comment">// 最开始默认值为false</span></span><br><span class="line"><span class="keyword">if</span> (!batchingStrategy.isBatchingUpdates) &#123;</span><br><span class="line">    batchingStrategy.batchedUpdates(enqueueUpdate, component);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">dirtyComponents.push(component);</span><br><span class="line"><span class="keyword">if</span> (component._updateBatchNumber == <span class="literal">null</span>) &#123;</span><br><span class="line">    component._updateBatchNumber = updateBatchNumber + <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></p>
<p>上面这段代码的意思就是如果是处于批量更新模式，也就是isBatchingUpdates为true时，不进行state的更新操作，而是将需要更新的component添加到dirtyComponents数组中；如果不处于批量更新模式，对所有队列中的更新执行batchedUpdates方法，然后往下看下去就知道是用事务的方式批量的进行component的更新。</p>
<p>然后可以找到了这个batchedUpdates：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> ReactDefaultBatchingStrategy = &#123;</span><br><span class="line">  <span class="comment">// 也就是上面提到的默认为false</span></span><br><span class="line">  isBatchingUpdates: <span class="literal">false</span>,</span><br><span class="line">  <span class="comment">// 这是一个方法，只有在isBatchingUpdates: false时才会调用</span></span><br><span class="line">  <span class="comment">// 但一般来说，出于react大事务中时会在render中的_renderNewRootComponent中将变为true。</span></span><br><span class="line">  batchedUpdates: <span class="function"><span class="keyword">function</span>(<span class="params">callback, a, b, c, d, e</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;</span><br><span class="line">    ReactDefaultBatchingStrategy.isBatchingUpdates = <span class="literal">true</span>;</span><br><span class="line">    <span class="comment">// The code is written this way to avoid extra allocations</span></span><br><span class="line">    <span class="keyword">if</span> (alreadyBatchingUpdates) &#123;</span><br><span class="line">      <span class="keyword">return</span> callback(a, b, c, d, e);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> transaction.perform(callback, <span class="literal">null</span>, a, b, c, d, e);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br></pre></td></tr></table></figure>
<p>看到这我总算理解了，当我们调用setState时，最终会通过enqueueUpdate执行state更新，就像上面那样有两种更新的模式，一种是批量更新模式，将组建保存在dirtyComponents;另一种非批量模式，将会遍历dirtyComponents，对每一个dirtyComponents调用updateComponent方法。就像这张图：</p>
<p><img src="https://gitee.com/uploads/images/2018/0528/145734_c2bb7d17_1575229.jpeg" alt="流程图" title="4fd1a155faedff00910dfabe5de143fc_hd.jpg"></p>
<p>至于批量与非批量模式，会通过ReactDefaultBatchingStrategy中的isBatchingUpdates属性来进行判断。在非批量模式下，会立即应用新的state；而在批量模式下，需要更新state的组件会被push 到dirtyComponents，再执行更新。</p>
<p>所以我们再看前面的那坨代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Example</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="keyword">super</span>();</span><br><span class="line">    <span class="keyword">this</span>.state = &#123;</span><br><span class="line">      val: <span class="number">0</span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  componentDidMount() &#123;</span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;<span class="attr">val</span>: <span class="keyword">this</span>.state.val + <span class="number">1</span>&#125;);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.val);    <span class="comment">// 第 1 次 log</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;<span class="attr">val</span>: <span class="keyword">this</span>.state.val + <span class="number">1</span>&#125;);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.val);    <span class="comment">// 第 2 次 log</span></span><br><span class="line"></span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">this</span>.setState(&#123;<span class="attr">val</span>: <span class="keyword">this</span>.state.val + <span class="number">1</span>&#125;);</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.val);  <span class="comment">// 第 3 次 log</span></span><br><span class="line"></span><br><span class="line">      <span class="keyword">this</span>.setState(&#123;<span class="attr">val</span>: <span class="keyword">this</span>.state.val + <span class="number">1</span>&#125;);</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="keyword">this</span>.state.val);  <span class="comment">// 第 4 次 log</span></span><br><span class="line">    &#125;, <span class="number">0</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>就不难看出它的答案是 0, 0, 2, 3。</p>
<p>总结起来就是这样：</p>
<ul>
<li>this.setState首先会把state推入pendingState队列中</li>
<li>然后将组件标记为dirty</li>
<li>React中有事务的概念，最常见的就是更新事务，如果不在事务中，则会开启一次新的更新事务，更新事务执行的操作就是把组件标记为dirty。</li>
<li>判断是否处于batch update</li>
<li>是的话，保存组建于dirtyComponent中，在事务结束的时候才会通过 ReactUpdates.flushBatchedUpdates 方法将所有的临时 state merge 并计算出最新的 props 及 state，然后将其批量执行，最后再关闭结束事务。</li>
<li>不是的话，直接开启一次新的更新事务，在标记为dirty之后，直接开始更新组件。因此当setState执行完毕后，组件就更新完毕了，所以会造成定时器同步更新的情况。</li>
</ul>
<p>另外还有就是updateComponent方法，这也很重要：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">&#123;   <span class="comment">// 会检测组件中的state和props是否发生变化，有变化才会进行更新; </span></span><br><span class="line">    <span class="comment">// 如果shouldUpdateComponent函数中返回false则不会执行组件的更新</span></span><br><span class="line">    updateComponent: <span class="function"><span class="keyword">function</span> (<span class="params">transaction,</span></span></span><br><span class="line"><span class="function"><span class="params">                               prevParentElement,</span></span></span><br><span class="line"><span class="function"><span class="params">                               nextParentElement,</span></span></span><br><span class="line"><span class="function"><span class="params">                               prevUnmaskedContext,</span></span></span><br><span class="line"><span class="function"><span class="params">                               nextUnmaskedContext,</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> inst = <span class="keyword">this</span>._instance;</span><br><span class="line">        <span class="keyword">var</span> nextState = <span class="keyword">this</span>._processPendingState(nextProps, nextContext);</span><br><span class="line">        <span class="keyword">var</span> shouldUpdate = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!<span class="keyword">this</span>._pendingForceUpdate) &#123;</span><br><span class="line">            <span class="keyword">if</span> (inst.shouldComponentUpdate) &#123;</span><br><span class="line">                <span class="keyword">if</span> (__DEV__) &#123;</span><br><span class="line">                    shouldUpdate = measureLifeCyclePerf(</span><br><span class="line">                            () =&gt; inst.shouldComponentUpdate(nextProps, nextState, nextContext),</span><br><span class="line">                            <span class="keyword">this</span>._debugID,</span><br><span class="line">                            <span class="string">'shouldComponentUpdate'</span>,</span><br><span class="line">                    );</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    shouldUpdate = inst.shouldComponentUpdate(</span><br><span class="line">                            nextProps,</span><br><span class="line">                            nextState,</span><br><span class="line">                            nextContext,</span><br><span class="line">                    );</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">this</span>._compositeType === CompositeTypes.PureClass) &#123;</span><br><span class="line">                    shouldUpdate =</span><br><span class="line">                            !shallowEqual(prevProps, nextProps) ||</span><br><span class="line">                            !shallowEqual(inst.state, nextState);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">    &#125;,</span><br><span class="line"><span class="comment">// 该方法会合并需要更新的state，然后加入到更新队列中</span></span><br><span class="line">    _processPendingState: <span class="function"><span class="keyword">function</span> (<span class="params">props, context</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> inst = <span class="keyword">this</span>._instance;</span><br><span class="line">        <span class="keyword">var</span> queue = <span class="keyword">this</span>._pendingStateQueue;  </span><br><span class="line">        <span class="keyword">var</span> replace = <span class="keyword">this</span>._pendingReplaceState;</span><br><span class="line">        <span class="keyword">this</span>._pendingReplaceState = <span class="literal">false</span>; </span><br><span class="line">        <span class="keyword">this</span>._pendingStateQueue = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!queue) &#123;</span><br><span class="line">            <span class="keyword">return</span> inst.state;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (replace &amp;&amp; queue.length === <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> queue[<span class="number">0</span>];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">var</span> nextState = <span class="built_in">Object</span>.assign(&#123;&#125;, replace ? queue[<span class="number">0</span>] : inst.state);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">var</span> i = replace ? <span class="number">1</span> : <span class="number">0</span>; i &lt; queue.length; i++) &#123;</span><br><span class="line">            <span class="keyword">var</span> partial = queue[i];</span><br><span class="line">            <span class="built_in">Object</span>.assign(</span><br><span class="line">                    nextState,</span><br><span class="line">                    <span class="keyword">typeof</span> partial === <span class="string">'function'</span></span><br><span class="line">                            ? partial.call(inst, nextState, props, context)</span><br><span class="line">                            : partial,</span><br><span class="line">            );</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> nextState;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>发现它会调用shouldComponentUpdate和componentWillUpdate方法，看到这不由理解了一个定律：不要在shouldComponentUpdate和componentWillUpdate中调用setState。如果在这两个生命周期里调用setState，会造成循环调用。</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/24/React组件的生命周期/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/05/24/React组件的生命周期/" itemprop="url">React组件的生命周期</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-24T17:43:59+08:00">
                2018-05-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/React/" itemprop="url" rel="index">
                    <span itemprop="name">React</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,554
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><p>这是会不断更新的一篇文章，因为随着对生命周期的理解的不断深入，势必要加上很多东西。</p>
<h3 id="一、组件生命周期的三个过程"><a href="#一、组件生命周期的三个过程" class="headerlink" title="一、组件生命周期的三个过程"></a>一、组件生命周期的三个过程</h3><p>了解React生命周期，对我们理解React的工作过程很有帮助。所有的事物都有自己的生命过程，React组件也不例外，同样有着自己的生命周期，通常而言它的生命会经历如下的三个过程：</p>
<ul>
<li>挂载过程</li>
<li>更新过程</li>
<li>销毁过程</li>
</ul>
<p>总的过程如下：</p>
<p><img src="https://pic3.zhimg.com/v2-05108ef8dd920d20cc00fd8eea8695ea_r.jpg" alt="生命周期"><br>转自：<a href="https://zhuanlan.zhihu.com/p/32387027" target="_blank" rel="noopener">https://zhuanlan.zhihu.com/p/32387027</a></p>
<p>在经历上面三个过程的时候，React库会一次调用组件的一些成员函数，这些函数称之为生命周期函数。因此，要定制一个react组件，实际上就是要定制这些生命周期函数。</p>
<h2 id="二、挂载过程"><a href="#二、挂载过程" class="headerlink" title="二、挂载过程"></a>二、挂载过程</h2><p>在挂载过程中，当组件第一次被渲染时，会依次调用以下函数：</p>
<ul>
<li>constructor</li>
<li>componentWillMount</li>
<li>render</li>
<li>componentDidMount</li>
</ul>
<h3 id="constructor-NaN"><a href="#constructor-NaN" class="headerlink" title="constructor"></a>constructor</h3><p>constructor也就是ES6语法中每个类的构造函数，而要创建一个组件类的实例，当然要调用对应的构造函数。但值得注意的是，不是每个React组件都需要定义自己的构造函数，使用构造函数一般都是以下两个原因：</p>
<ol>
<li>初始化state。因为组件中的任何函数都可能需要访问state，因此在constructor中来初始化state是很好的选择。</li>
<li>绑定成员函数的this。在es6中，累的每个成员函数在执行时的this并不是和类的实例所绑定的。而在钩子凹函数中，this就是当前组件实例。所以，在此绑定this可以方便未来的调用。</li>
</ol>
<h3 id="componentWillMount"><a href="#componentWillMount" class="headerlink" title="componentWillMount"></a>componentWillMount</h3><p>在挂载过程中，componentWillMount会在render函数之前被调用。但通常来讲我们不需要来定义componentWillMount，我们可以认为它所需要做的事情我们一般都在constructor中来做了。它所存在的意义更多的是为了与我们后面会提到的componentDidMount对称。但也有一些组件启动的动作，包括像 Ajax 数据的拉取操作、一些定时器的启动等，就可以放在 componentWillMount 里面进行。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">componentWillMount () &#123;</span><br><span class="line">  ajax.get(<span class="string">'http://json-api.com/user'</span>, (userData) =&gt; &#123;</span><br><span class="line">    <span class="keyword">this</span>.setState(&#123; userData &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="render"><a href="#render" class="headerlink" title="render"></a>render</h3><p>rende 函数是 React 组件中最重要的函数。它并不是直接去渲染动作，而是返回一个 JSX 描述的结构，然后最终由 React 来渲染过程。</p>
<p>对于render函数需要注意以下两点：</p>
<ul>
<li>首先是我们在定义React组件的时候，可以忽略其他所有组件都不实现，但一定要实现render，因为所有React组件的父类对除了render函数之外的生命周期函数都有默认实现。</li>
<li>其次render函数应该是一个纯函数，应该完全根据this.state和this.props来决定返回的结果，而不应该产生任何副作用。因此，不应该在render中调用this.setState，这会引起状态的变化。</li>
</ul>
<p>另外还有一点需要注意，就是无论是挂载过程还是更新过程，都是以 render 函数为边界。在 render 之前的生命周期函数并没有真正的更新，而是只是作为一个参数，只有当 render 函数执行后，组件内部的 props 和 state 才会发生改变。这符合 React16 的 Fiber 的思路，因为Fiber中一个组件在执行时不一定会一次性的执行完，因此在没有渲染完成前可能会将 render 之前的生命周期函数执行多次，当这种情况发生时，如果 render 之前的生命周期函数会影响到 props 和 state，那么就会产生很多意想不到的副作用。</p>
<h4 id="componentDidMount"><a href="#componentDidMount" class="headerlink" title="componentDidMount"></a>componentDidMount</h4><p>在 render 函数调用完之后 componentDidMount 函数并不会马上被调用。它会在 render 函数返回的东西已经引发了渲染，组件已经被挂载到DOM树上时才会被调用。</p>
<p>前面提到的 render 函数知识返回 JSX，并不负责直接的渲染，因此 React 库需要把所有组件返回的结果全部集合起来，才可以知道如何产生对应的 DOM 修改。因此才会需要 componentDidMount 函数在 render 返回 JSX，组件被渲染了才会调用来收尾。</p>
<p>它还有一个与 componentWillMount 函数不同的是，它只能在浏览器端被使用，而 componentWillMount 则可以使用在服务器端与浏览器端。这是由于只有浏览器端才会发生渲染的原因，服务器端可不会发生组件的挂载。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Header</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span> () &#123;</span><br><span class="line">    <span class="keyword">super</span>()</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'construct'</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  componentWillMount () &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'component will mount'</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  componentDidMount () &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'component did mount'</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render () &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'render'</span>);</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">        &lt;h1 className=<span class="string">'title'</span>&gt;我是Srtian&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp">      &lt;/</span>div&gt;</span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">construct                     index.js:<span class="number">15</span></span><br><span class="line">component will mount          index.js:<span class="number">19</span></span><br><span class="line">render                        index.js:<span class="number">27</span></span><br><span class="line">component did mount           index.js:<span class="number">23</span></span><br></pre></td></tr></table></figure>
<h2 id="三、更新过程"><a href="#三、更新过程" class="headerlink" title="三、更新过程"></a>三、更新过程</h2><p>当挂载过程结束之后，用户们便可以看见我们的页面了。但出于用户体验的角度来看，我们还需要提供更好的交互体验，我们就需要组件可以随着用户操作来改变页面内容，而 props 和 state 的修改，组件就会引发生更新过程。<br>更新过程包括以下生命周期函数：</p>
<ul>
<li>componentWillReceiveProps：组件从父组件接收到新的 props 之前调用。</li>
<li>shouldComponentUpdate(nextProps, nextState)：你可以通过这个方法控制组件是否重新渲染。如果返回 false 组件就不会重新渲染。这个生命周期在 React.js 性能优化上非常有用。</li>
<li>componentWillUpdate：组件开始重新渲染之前调用。</li>
<li>componentDidUpdate：组件重新渲染并且把更改变更到真实的 DOM 以后调用。</li>
</ul>
<h3 id="componentWillReceiveProps"><a href="#componentWillReceiveProps" class="headerlink" title="componentWillReceiveProps"></a>componentWillReceiveProps</h3><p>值得注意的是，更新过程有两种方式一种是外部的父组件渲染，子组件也会进行更新，另一种是组件内部的 state 更新。这两个更新不同的是在内部的 state 更新所引发的更新过程，生命周期函数 componentwillReceiveProps 不会被调用，子组件收到新的 props 之后会触发的函数。通过它的名字其实我们就可已看出，它只是will，而不会去更改 props 的值。</p>
<p>有人在网上说，这个函数只有在组件的 props 函数发生改变时才会调用这个函数。其实不然，实际上，只要父组件的 render 函数被调用，在render 函数里面被渲染的子组件都会经历更新过程，componentWillReceiveProps 函数也就会触发。因此当我们不希望因为父组件的render 函数调用就引起子组件更新时，就需要使用下面这个 shouldComponentUpdate 来进行判断，是否需要进行更新过程。</p>
<p>而且，通过 this.setState 方法出发的更新过程也不会触发该函数。这是由于这个函数适合更具新得 props 值来计算出是不是要更新内部状态的 state。而 this.setState 就是用于更新组件的内部状态的，这会引起死循环。</p>
<h3 id="shouldComponentUpdate"><a href="#shouldComponentUpdate" class="headerlink" title="shouldComponentUpdate"></a>shouldComponentUpdate</h3><p>shouldComponentUpdate 是一个很特殊的函数，它决定了一个组件什么时候不需要渲染。它是除了 render 函数之外最重要的函数了。</p>
<p>他们两个也是 React 生命周期函数中唯二要求返回结果的函数。其中 render 函数的返回结果用于构造DOM对象，而它会返回同一个布尔值，默认会返回 ture，但假如这个函数返回 false 的话，更新流程就会被跳过，render 也不会继续被触发。</p>
<p>说 shouldComponentUpdate 重要就是由于只要利用的好，我们可以在这个函数中自定义一些判断来跳过不需要被更新的组件，从而提升性能。</p>
<h3 id="componentWillUpdate和componentDidUpdate"><a href="#componentWillUpdate和componentDidUpdate" class="headerlink" title="componentWillUpdate和componentDidUpdate"></a>componentWillUpdate和componentDidUpdate</h3><p>componentWillUpdate 和 componentDidUpdate 分别会在 render 的前后被触发。</p>
<h4 id="componentWillUpdate"><a href="#componentWillUpdate" class="headerlink" title="componentWillUpdate"></a>componentWillUpdate</h4><p>componentWillUpdate 无法调用 this.setState()，我们可以理解为更新流程到这一步想要再更改state已经晚了。如果有需要，我们可以在之前的 componentWillReceiveProps 中更新 state，React 会把所有的更改合并到一个更新流程里进行。</p>
<h4 id="componentDidUpdate"><a href="#componentDidUpdate" class="headerlink" title="componentDidUpdate"></a>componentDidUpdate</h4><p>componentDidUpdate 则是另一个比较适合我们发起 ajax 请求的地方，在这个方法里我们还可以比较前后的props变化，再决定是否发起网络请求。一个比较实际的使用场景是保存用户输入到服务器，用户可能会来来回回修改输入的内容，但假如我们判断在修改前后数据最终没有改变，就没有必要发起不必要的网络请求了。我们也可以通过它来来调用其他的UI库。而且他也可以在服务器端来调用，因为服务器端中使用 React 基本不会经历更新过程，所有也就无所谓了。</p>
<h2 id="四、卸载过程"><a href="#四、卸载过程" class="headerlink" title="四、卸载过程"></a>四、卸载过程</h2><h3 id="componentWillUnmount"><a href="#componentWillUnmount" class="headerlink" title="componentWillUnmount"></a>componentWillUnmount</h3><p>在卸载流程中，名为 componentWillUnmount 的函数会被触发。在组件挂载之后，我们可能定义了一些计时器、绑定了事件监听函数等等，在卸载流程的生命周期函数中，也是我们解绑这些函数的合适位置。</p>
<p>它的工作也一般和 componentDidMount 有关。比如，在 componentDidMount 中用非 React 的方法创造一些DOM元素，如果撒手不管就可能造成内存泄漏，这就需要 componentWillUnmount 函数来吧这些创造的DOM元素清理掉。</p>
<h2 id="五、新增的生命周期函数"><a href="#五、新增的生命周期函数" class="headerlink" title="五、新增的生命周期函数"></a>五、新增的生命周期函数</h2><h3 id="componentDidCatch"><a href="#componentDidCatch" class="headerlink" title="componentDidCatch"></a>componentDidCatch</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">componentDidCatch(error, info)</span><br></pre></td></tr></table></figure>
<p>这是 React 16 新加入的一个生命周期函数。定义该生命周期函数的组件将会成为一个错误边界，错误边界这个词非常形象，它可以有效地将错误限制在一个有限的范围内，而不会导致整个应用崩溃，防止一颗耗子屎坏了一锅汤。</p>
<p>错误边界组件，可以捕获其整个子组件树内发生的任何异常，但是却不能捕获自身的异常</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/22/聊一聊基本的MVVM设计思想/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/05/22/聊一聊基本的MVVM设计思想/" itemprop="url">聊一聊基本的MVVM设计思想</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-22T18:04:06+08:00">
                2018-05-22
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Vue/" itemprop="url" rel="index">
                    <span itemprop="name">Vue</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  930
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  3
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="一、为什么我们需要MVVM"><a href="#一、为什么我们需要MVVM" class="headerlink" title="一、为什么我们需要MVVM"></a>一、为什么我们需要MVVM</h3><p>在写界面时，我们经常会碰到一些功能，需要数据生成页面，然后页面通过输入控件收集的数据的改变，经过改变后再次更新页面。就比如一个数组和一个页面上的列表，我们通常会需要这个数组与列表相对应，当数组改变时，页面中的列表可以发生改变。而当列表发生改变时，数组可以通过输入控件，将数据进行改变然后再渲染页面上的列表。</p>
<p>整个这个过程，说起来很绕口，其实归纳来看，就在做两件事：</p>
<ul>
<li>根据数据的变动，生成或者变更界面</li>
<li>根据界面的操作，变更数据。</li>
</ul>
<p>既然已经将它们的操作过程归纳起来了，那么如果我们引入一种绑定关系，通过一系列的配置过程后，使得以后的每次数据发生变更时，页面也会发生相应的更新；而页面上的操作也会自动更新到数据。这会让我们开发变得更为方便，有老婆孩子的可以省下时间去陪老裴孩子，没老婆孩子的可以省下时间去打游戏（没错，我就是后者，泪奔~）。而MVVM就是提供了这么一套配置，为我们建立了数据和界面的关联关系。</p>
<h3 id="二、-MVVM的构成"><a href="#二、-MVVM的构成" class="headerlink" title="二、 MVVM的构成"></a>二、 MVVM的构成</h3><p>MVVM的全名是Model-View-ViewModel，它的基本思路就是这样：</p>
<p><img src="https://gitee.com/uploads/images/2018/0624/143106_17c7f1d8_1575229.png" alt="image"></p>
<p>它分为三部分：</p>
<ul>
<li>Model</li>
<li>View</li>
<li>ViewModel</li>
</ul>
<h4 id="2-1-Model"><a href="#2-1-Model" class="headerlink" title="2.1 Model"></a>2.1 Model</h4><p>model很好理解，就是指数据层，是纯净的数据。对于前端来说，model往往是一个简单的对象。比如这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    name: <span class="string">"srtian"</span>,</span><br><span class="line">    age: <span class="number">22</span>,</span><br><span class="line">    like: &#123;</span><br><span class="line">        sports: [<span class="string">"football"</span>, <span class="string">"run"</span>],</span><br><span class="line">        music: <span class="string">"You're Beautiful"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>简单来说，数据层就是我们要渲染后呈现给用户的数据，数据层本身是可变的，且不用承担逻辑操作和计算的功能。</p>
<h4 id="2-2-View"><a href="#2-2-View" class="headerlink" title="2.2 View"></a>2.2 View</h4><p>View也很简单，就是指视图层，也就是直接呈现给用户的那部分，对前端就是HTML。比如上面的数据层，它所对应的视图层可能是这样的：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">b</span>&gt;</span>name: <span class="tag">&lt;/<span class="name">b</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">span</span>&gt;</span>srtian<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">b</span>&gt;</span>age: <span class="tag">&lt;/<span class="name">b</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">span</span>&gt;</span>22<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>like:<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span>&gt;</span>football<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span>&gt;</span>run/li&gt;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span>&gt;</span>You're Beautiful<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>当然视图层并不是固定的，而是可变的，我们可以随意的添加元素。而这在MVVM中并不会改变数据层，而是改变了视图层呈现数据的方式。同时需要注意的是，视图层应该和数据层完成分离。</p>
<h4 id="2-3-ViewModel"><a href="#2-3-ViewModel" class="headerlink" title="2.3 ViewModel"></a>2.3 ViewModel</h4><p>既然视图层应该和数据层相分离，那么我们就需要设计一种结构，让他们建立起某种联系，Vue官网上的这张图就很好的解释了ViewModel的作用：</p>
<p><img src="https://gitee.com/uploads/images/2018/0624/143106_17c7f1d8_1575229.png" alt="image"></p>
<p>抛开ViewModel本身带有的一些属性外，ViewModel本身其实主要是做了两件事：</p>
<ul>
<li>从Model到View的映射，也就是Data Binding。这样可以大量省略我们手动update View的代码和时间。</li>
<li>从 View 到 Model 的事件监听,也就是DOM Listeners。这样我们的 Model 就会随着 View 触发事件而改变。</li>
</ul>
<h3 id="三、小结"><a href="#三、小结" class="headerlink" title="三、小结"></a>三、小结</h3><p>综上所述，我们知道了MVVM所包含的Model，View，ViewModel三层，在实践的时候，主要包含几个要点：</p>
<ul>
<li>以不同的角色分别考虑每个层次，划定它们所负责的范围</li>
<li>先划分Model和View，最后考虑ViewModel，利用ViewModel将其两者联系起来。</li>
</ul>
<p>参考资料：<br><a href="https://zhuanlan.zhihu.com/p/24475845" target="_blank" rel="noopener">https://zhuanlan.zhihu.com/p/24475845</a></p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/21/JavaScript设计模式之观察者模式/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/05/21/JavaScript设计模式之观察者模式/" itemprop="url">JavaScript设计模式之观察者模式</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-21T22:30:16+08:00">
                2018-05-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,253
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>准备研究一下MVVM的一些东西，由于MVVM运用了观察者模式的思想，因此翻开了《JavaScript设计模式与开发实践》一书，将观察者模式学习了一遍，顺便有对一些常用的设计模式进行一些了解，但由于平时很多设计模式并没有用过甚至没有接触过，发现一个很有意思的东西，JavaScript还正是厉害，将很多常用的设计模式都封装成了API，比如ES6出来的迭代器和代理。但总的来说还是有很多不能理解的地方，真是前途漫漫，还需努力啊。</p>
<h3 id="一、什么是观察者模式"><a href="#一、什么是观察者模式" class="headerlink" title="一、什么是观察者模式"></a>一、什么是观察者模式</h3><p>观察者模式又叫做发布—订阅模式，是我们最常用的设计模式之一（这两种模式其实还是有一定区别，但在《JavaScript设计模式与开发实践》一书中有这么说过，但在经历了一些学习后发现这两种还是存在一定的区别的，具体区别可以谷歌~）。它定义对象间的一种一对多的依赖关系，当一个对象的状态发生改变时，所有依赖于它的对象都将得到通知和更新。观察者模式提供了一个订阅模型，其中对象订阅事件并在发生时得到通知，这种模式是事件驱动的编程基石，它有利益于良好的面向对象的设计。</p>
<p>看了上面的这段描述，可能还是不懂什么是观察者模式。我们还可以来看看生活中的观察者模式：现在房价这么高，你肯定是想要早点买房，但你看好的楼盘还没开盘，因此你就将你的电话留给售楼小姐，一旦楼盘推出就让她打电话给你。主动权在售楼方，而你只需要提供一个联系方式就行了这样你就不用担心楼盘出来你不知道了，也不需要每天都打电话去问楼盘推出了没。</p>
<p>自己的一些理解：学了Rx.js后对观察者模式有了更为深刻的理解，观察者模式本质上就是将数据的产生于数据的处理逻辑相分离开来，被观察者模式负责数据的产生，观察者则负责处理数据，即产生的数据流与处理数据的逻辑分离开来。（补充）</p>
<h3 id="二、观察者模式的使用场景"><a href="#二、观察者模式的使用场景" class="headerlink" title="二、观察者模式的使用场景"></a>二、观察者模式的使用场景</h3><h4 id="2-1-DOM事件"><a href="#2-1-DOM事件" class="headerlink" title="2.1 DOM事件"></a>2.1 DOM事件</h4><p>实际上，只要我们曾经在DOM节点上面绑定过事件函数，那我们就使用过观察者模式，应为JS和DOM之间就是实现了一种观察者模式。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.body.addEventListener(<span class="string">"click"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    alert(<span class="string">"Hello World"</span>)</span><br><span class="line">&#125;，<span class="literal">false</span> )</span><br><span class="line"><span class="built_in">document</span>.body.click() <span class="comment">//模拟用户点击</span></span><br></pre></td></tr></table></figure>
<p>在上面的代码中，需要监听用户点击 document.body 的动作，但是我们是没办法预知用户将在什么时候点击的。因此我们订阅了 document.body 的 click 事件，当 body 节点被点击时，body 节点便会向订阅者发布 “Hello World” 消息。</p>
<h4 id="2-2自定义事件"><a href="#2-2自定义事件" class="headerlink" title="2.2自定义事件"></a>2.2自定义事件</h4><p>除了DOM事件外，我们还可以实现一些自定义事件，这种依靠自定义时间完成的观察者模式可以用于任何的JavaScript代码中。</p>
<p>示例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> event = &#123;</span><br><span class="line">    clientList: [],</span><br><span class="line">    listen: <span class="function"><span class="keyword">function</span>(<span class="params">key, fn</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.clientListen[key]) &#123;</span><br><span class="line">            <span class="keyword">this</span>.clientList[key] = []</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.clientList[key].push(fn)</span><br><span class="line">    &#125;,</span><br><span class="line">    trigger: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> key = <span class="built_in">Array</span>.prototype.shift.call(<span class="built_in">arguments</span>)</span><br><span class="line">        <span class="keyword">const</span> fns = <span class="keyword">this</span>.clientList[key]</span><br><span class="line">        <span class="keyword">if</span> (!fns || fns.length === <span class="number">0</span> ) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, fn ;fn = fns[i++];) &#123;</span><br><span class="line">            fn.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    remove : <span class="function"><span class="keyword">function</span>(<span class="params">key , fn</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> fns = <span class="keyword">this</span>.clientList[key]</span><br><span class="line">        <span class="keyword">if</span> (!fns) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (!fn) &#123;</span><br><span class="line">            fns &amp;&amp; (fns.length = <span class="number">0</span>)</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">let</span> l = fns.length - <span class="number">1</span>; l&gt;=<span class="number">0</span>; l--) &#123;</span><br><span class="line">                <span class="keyword">const</span> _fn = fns[l]</span><br><span class="line">                <span class="keyword">if</span> ( _fn === fn) &#123;</span><br><span class="line">                    fns.splice(l, <span class="number">1</span>)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> installEvent = <span class="function"><span class="params">obj</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i <span class="keyword">in</span> event) &#123;</span><br><span class="line">        obj[i] = event[i]</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后我们就能增加发布和订阅功能了：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> events = &#123;&#125;</span><br><span class="line">installEvent(events)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 订阅信息</span></span><br><span class="line">events.listen(<span class="string">'newMessage'</span>, fn1 = <span class="function"><span class="params">say</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'say:'</span> + say)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 发布信息</span></span><br><span class="line">events.trigger(<span class="string">'newMessage'</span>, <span class="string">"Hello world"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//移除订阅</span></span><br><span class="line">events.remove(<span class="string">'newMessage'</span>, fn1)</span><br></pre></td></tr></table></figure>
<h3 id="三、观察者模式的不足"><a href="#三、观察者模式的不足" class="headerlink" title="三、观察者模式的不足"></a>三、观察者模式的不足</h3><p>观察者模式的有点非常明显：一是时间上的解耦，而是对象之间的解耦。既可用于异步编程中，也可以用帮助我们完成更松耦合的代码编写。但它仍然有所不足：</p>
<ul>
<li>创建订阅者本身要消耗一定的时间和内存</li>
<li>当订阅一个消息时，也许此消息并没有发生，但这个订阅者会始终存在内存中。</li>
<li>观察者模式弱化了对象之间的联系，这本是好事情，但如果过度使用，对象与对象之间的联系也会被隐藏的很深，会导致项目的难以跟踪维护和理解。</li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/18/钗头凤/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/05/18/钗头凤/" itemprop="url">钗头凤 ——记放翁，唐氏</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-18T21:53:41+08:00">
                2018-05-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/随笔/" itemprop="url" rel="index">
                    <span itemprop="name">随笔</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  60
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  1
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>沈园内，白阁边。</p>
<p>烟柳画池波微皱。</p>
<p>桃花瘦，别情素。</p>
<p>一曲离歌，两段闲愁。</p>
<p>过 过 过</p>
<p>春又至，横倚栏。</p>
<p>黄藤酒中泪已满。</p>
<p>花飞落，月西楼。</p>
<p>昔人虽逝，此情难忘。</p>
<p> 错 错 错</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/18/醉花间/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/05/18/醉花间/" itemprop="url">醉花间</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-18T21:53:21+08:00">
                2018-05-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/随笔/" itemprop="url" rel="index">
                    <span itemprop="name">随笔</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  50
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  1
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>门前雪落春未到，径边梅自闹。</p>
<p>归雁将筑巢，寒风卷枯草。</p>
<p>山光无限好，西江自流去</p>
<p>青丝成华发。</p>
<p>前路莫愁知己少。</p>
<p>途漫漫，雪飘飘。</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/18/点绛唇/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/blog/2018/05/18/点绛唇/" itemprop="url">点绛唇</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-18T21:51:21+08:00">
                2018-05-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/随笔/" itemprop="url" rel="index">
                    <span itemprop="name">随笔</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  41
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  1
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>半夜酒醒，风卷残帘春愁去。</p>
<p>昼夜无眠，空对烛光语。</p>
<p>莺谛丹香，春至凭栏处。</p>
<p>侧身望。</p>
<p>凌波未至，零落樱花雨。</p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/blog/page/3/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/blog/">1</a><span class="space">&hellip;</span><a class="page-number" href="/blog/page/3/">3</a><span class="page-number current">4</span><a class="page-number" href="/blog/page/5/">5</a><a class="page-number" href="/blog/page/6/">6</a><a class="extend next" rel="next" href="/blog/page/5/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  

  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
